<template>
  <div class="row">
    <div class="col-lg-12">
      <div class="main-box clear-fix">
        <header class="main-box-header clearfix">
          <h2 class="pull-left">{{title}}</h2>
          <slot name="header"></slot>
        </header>
        <div class="main-box-body clearfix">
          <div class="table-responsive">
            <table class="table table-hover">
              <thead v-if="columns">
                <tr>
                  <th v-for="key in columns" track-by="$index"><a href="#" :class="{'asc': sortOrders[$index] < 0, 'desc': sortOrders[$index] > 0}" @click="_sortBy($index)"><span>{{key}}</span></a></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in renderData | limitBy maxRow | filterBy filterKey | orderBy sortKey _sortOrder(sortKey)" track-by="$index">
                  <template v-if="row.el">
                    <template v-for="cell in row.el">
                      <td v-if="typeof cell == 'string'">{{{cell}}}</td>
                      <td v-else>
                        <span v-for="item in cell" @click="action(row.id, item, row)">{{{item.el}}}</span>
                      </td>
                    </template>              
                  </template>
                  <template v-else>
                      <td v-for="cell in row">{{cell}}</td>
                  </template>

                </tr>
              </tbody>
            </table>
          </div>
          <!-- 分页 -->
          <ul class="pagination pull-right" v-if="totalPage != 1">
            <li @click="prevPage"><a><i class="fa fa-chevron-left"></i></a></li>
            <li v-for="n in totalPage" @click="goPage(n+1)"><a>{{n+1}}</a></li>
            <li @click="nextPage"><a><i class="fa fa-chevron-right"></i></a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  import _ from 'lodash'

  /**
   * Datas format
   * {
   *   totalSize: Number,
   *   data: Array[Object],
   *   resultSize: Array(data.length)
   * }
   */
  
  export default {

    name: 'vita-table',

    props: {
      datas: {
        coerce(val) {
          //将数据统一转换
          if (_.isArray(val)) {
            return {
              totalSize: val.length,
              data: val,
              resultSize: val.length
            }
          } 

          return val
        }
      },
      //最大显示行数
      maxRow: {
        type: Number,
        default: 10
      }, 
      // 过滤关键字
      filterKey: String,
      //表格头
      columns: Array,
      // 表格名称
      title: String,

      dataSourceUrl: String,

      processResponseData: Function,

      serverSide: Boolean
    },

    data() {

      let sortOrders = {}
      _.each(_.range(this.columns.length), function(value, index) {
        sortOrders[index] = 0
      })

      return {
        // 当前页数
        page: 1,
        filterModel: '',
        sortOrders,
        sortKey: ''
      }
    },

    watch: {
      page: function(val, oldVal) {
        console.log('page:', val)
        if (this.serverSide) {
          console.log('服务器获取数据')
          this._fetchServerSideData({start: (val - 1) * this.maxRow, length: this.maxRow})
        }
      }
    },

    //页数从1开始
    methods: {
      // 内部方法
      // 检测当前页数是否超出边界
      _pageOverRange(page) {
        return page < 1 || page > this.totalPage
      },
      // 页面跳转
      goPage(page) {
        if (!this._pageOverRange(page)) {
          this.page = page
        }
      },

      prevPage() {
        this.goPage(this.page - 1)
      },

      nextPage() {
        this.goPage(this.page + 1)
      },

      action(id, cell, params) {
        this.$dispatch('vita-table:' + cell.event, params)
      },
      //排序（通过列编号找到对应的字段进行排序）
      _sortBy(index) {
        let keys = _.keys(this.renderData[0])
        this.sortKey = keys[index]
        let order = this.sortOrders[index]
        switch (order) {
          case 0:
            this.sortOrders[index] = 1
            break;
          case 1:
            this.sortOrders[index] = -1
            break;
          case -1:
            this.sortOrders[index] = 0
        }
      },

      _sortOrder(key) {
        let keys = _.keys(this.renderData[0])
        return this.sortOrders[_.indexOf(keys, key)]
      },

      //拉取服务端数据
      _fetchServerSideData(request) {

        var start = request.start || 0
        var offset = request.offset || this.maxRow
        var order = request.order || ''
        // console.log({start, length, order})
        this.$http.get(this.dataSourceUrl, {start, offset, order}).then((response)=> {

          if (this.serverSide && this.processResponseData) {
            this.processResponseData(response.data, (formatData)=> {
              this.datas = formatData
              return formatData
            })
          } else {
            this.datas = response.data
          }

        })
      }

    },

    computed: {
      // 总页数
      totalPage(){

        let pages, data

        data = _.isEmpty(this.datas) ? {totalSize: 0} : this.datas
        pages = (this.serverSide ? data.totalSize : data.data.length) / this.maxRow

        return pages <= 1 ? 1 : Math.ceil(pages)

      },
      // 渲染到表格的数据
      renderData() {

        if (!this.datas) return []

        let gridData = this.datas
        let renderData



        if (this.serverSide) {
          renderData = gridData.data
        } else {
          let start = this.maxRow * (this.page - 1)
          let end = start + this.maxRow
          renderData = gridData.data.slice(start, end)
        }

        return renderData
      }
    },

    compiled() {

      if (this.serverSide) {
        this._fetchServerSideData({start: 0, offset: 10})
      }

    }

  }

</script>